<?php
require_once(classdir.'commons.php');
require_once(classdir.'user.php');
require_once(classdir.'roles.php');

class users extends commons{
	var	$tbl = "users",
			$tblUserGroup = "user_group";
	var $items = array();
	var $roles = array();
	
	function get_items($conditions=array(),$limit=0,$order="login",$search_string=''){
		global $db;
		$return = false;
		$this->items = array();
		$where_arr = array();
		$fileds = "";
		$join = "";
		if (isset($conditions['group_id'])){
			$fields = ", ug.percent,ug.mark,ug.type,ug.group_id";
			$join = "
				INNER JOIN 
					$this->tblUserGroup as ug
				ON
					ug.user_id=u.id
			";
/*					AND 
					ug.group_id=".(int)$conditions['group_id']."
			";
			unset($conditions['group_id']);
*/
		}
		foreach($conditions as $key=>$value){
			$key = block($key);
			$value = block($value);
			$where_arr[] = $key." = '$value'";
		}
		if (!empty($where_arr)){
         $where = " WHERE (".implode(") AND (",$where_arr).")";
		}
		$search_string = block(trim($search_string));
		$search_sql =
							empty($search_string)?
							"":
							"AND (
								u.login LIKE '%$search_string%'
								OR
								u.name LIKE '%$search_string%'
							)";

		$this->items = array();
		$sql = "
			SELECT SQL_CALC_FOUND_ROWS
				u.id,	u.login,	u.name,	u.surname,	u.address,	u.city,	u.state,
				u.cp,	u.phone,	u.mail,	u.sex,		u.birthday,	u.dni,	u.nss,
				u.invalid,	u.study_level,		u.functional_area, 	u.professional_category,
				u.price_group,		u.company_id,	u.role_id
				$fields
			FROM
				$this->tbl as u 
				$join
		".$where;
		if (!empty($search_sql)){
			$sql .= $search_sql;
		}

		$sql .= (!empty($order)?" ORDER BY ".block($order):"");

		if (is_array($limit)){
			$sql .= " LIMIT ".(int)$limit[0].",".(int)$limit[1];
		}elseif ($limit!=0){
			$sql .= " LIMIT ".(int)$limit;
		}
		$users = $db->query_assoc_count($sql,$count,'id');
		if ($users) :
			foreach ($users as $id=>$user) :
				$this->items[$id] = new user($user);
			endforeach;			
		endif;
		
		return $count;
	}
	
	function get_roles(){
		$return = false;
		if (!is_object($this->roles)){
			$roles_obj = new roles();
			$roles_obj->get_items();
			$this->roles = &$roles_obj->items;
			$return = true;
		}else{
			$return = true;
		}
		return $return;
	}

	function url($echo=true){
		$return = url.get_class($this).'/';
		if ($echo){
			echo $return;
		}
		return $return;
	}
	
	function url_edit($echo=true,$id=null){
		$return = url.get_class($this).'/edit/'.$id.'/';
		if ($echo){
			echo $return;
		}
		return $return;
	}
	
	function url_delete($echo=true,$id=null){
		$return = url.get_class($this).'/delete/'.$id.'/';
		if ($echo){
			echo $return;
		}
		return $return;
	}
}
?>